<template>
  <div class="citylist">
    <div class="citylist-one">
      <van-icon
        name="arrow-left"
        @click="
          () => {
            this.$router.push('/home');
          }
        "
      />
      <h3>城市选择</h3>
      <span></span>
    </div>

    <van-index-bar :sticky="false" :index-list="az">
      <div v-for="(v, i) in citylist" :key="i">
        <van-index-anchor :index="v.title" />
        <van-cell
          v-for="(item, index) in v.children"
          :key="index"
          :title="item.label"
          @click="goHome(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      citylist: [],
      az: []
    }
  },
  methods: {
    ...mapMutations(['setCity']),

    goHome (item) {
      //
      console.log(item)
      this.setCity(item)
      this.$router.push('/home')
    }
  },
  created () {
    this.$http.get('/area/city?level=1').then((res) => {
      const city1 = res.data.body
      const city2 = [...city1] // 过滤出来a-z
      const A_Z = city2.map((v) => {
        return v.short.slice(0, 1).toUpperCase()
      })
      const set = [...new Set(A_Z)] // 去重
      const initAz = set.sort() // 首字母组成的数组
      const indexList = [...initAz]
      this.az = indexList
      initAz.forEach((v, i) => { // 遍历首字母
        const arr = city1.filter((item) => { // 拿到每个首字母对应的城市数据
          return item.short.slice(0, 1).toUpperCase() === v
        })
        initAz[i] = {
          title: v,
          children: [...arr]
        }
      })
      this.citylist = initAz
    })
  }
}
</script>

<style>
.citylist {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.citylist-one {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background: #e6e6e6;
  font-size: 16px;
}
.van-index-bar{
  width: 100%;
  flex: 1;
  overflow-y: scroll;
}
</style>
